package com.dpj.reentranloock_test;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

@Slf4j(topic = "c.Test2")
public class Test2 {
    //加入interrupt可以线程被打断，防止无限等待，这也是防止死锁的一种方式
    private  static ReentrantLock lock=new ReentrantLock();
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            try {
                //如果没有竞争那么此方法就会获取 lock对象锁
                //如果有竞争就进入阻塞队列，可以被其他线程用 interrupt方法打断
                log.debug("尝试获得锁");
                lock.lockInterruptibly();
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.debug("被打断，没有获得锁,返回");
                return;
            }
            try {
                log.debug("获取到锁");
            }finally {
                lock.unlock();
            }

        },"t1");

        lock.lock();
        t1.start();
        Thread.sleep(1000);
        log.debug("打断t1");
        t1.interrupt();

    }
}
